<template>
  <div class="workflow-management">
    <div class="search-section">
      <el-card class="search-card" shadow="never">
        <div class="search-form">
          <el-form :model="searchForm" inline>
            <el-form-item label="流程标题">
              <el-input
                v-model="searchForm.title"
                placeholder="请输入流程标题"
                clearable
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item label="流程类型">
              <el-select
                v-model="searchForm.type"
                placeholder="请选择流程类型"
                clearable
                style="width: 150px"
              >
                <el-option label="请假申请" value="leave" />
                <el-option label="报销申请" value="reimbursement" />
                <el-option label="出差申请" value="business" />
                <el-option label="采购申请" value="purchase" />
                <el-option label="其他申请" value="other" />
              </el-select>
            </el-form-item>
            <el-form-item label="流程状态">
              <el-select
                v-model="searchForm.status"
                placeholder="请选择状态"
                clearable
                style="width: 120px"
              >
                <el-option label="草稿" value="draft" />
                <el-option label="审批中" value="pending" />
                <el-option label="已通过" value="approved" />
                <el-option label="已拒绝" value="rejected" />
                <el-option label="已撤回" value="withdrawn" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch" :loading="loading">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button @click="handleReset">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <el-card class="table-card" shadow="never">
        <template #header>
          <div class="table-header">
            <div class="header-left">
              <span class="table-title">我的流程</span>
              <el-tag type="info" size="small">{{ total }} 条记录</el-tag>
            </div>
            <div class="header-right">
              <el-button type="primary" @click="handleCreate" :loading="loading">
                <el-icon><Plus /></el-icon>
                新建流程
              </el-button>
              <el-button @click="handleRefresh" :loading="loading">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </div>
        </template>

        <el-table
          v-loading="loading"
          :data="workflowList"
          stripe
          border
          style="width: 100%"
          class="workflow-table"
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="title" label="流程标题" min-width="200">
            <template #default="{ row }">
              <div class="title-cell">
                <span 
                  :class="{ 'urgent-title': row.priority === 'high' }"
                  @click="handleViewDetail(row)"
                >
                  {{ row.title }}
                </span>
                <el-tag v-if="row.priority === 'high'" type="danger" size="small">紧急</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="流程类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getTypeTagType(row.type)" size="small">
                {{ getTypeLabel(row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="流程状态" width="120">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status)" size="small">
                {{ getStatusLabel(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="current_approver" label="当前审批人" width="120" />
          <el-table-column prop="create_time" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatTime(row.create_time) }}
            </template>
          </el-table-column>
          <el-table-column prop="update_time" label="更新时间" width="180">
            <template #default="{ row }">
              {{ formatTime(row.update_time) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="handleViewDetail(row)">
                <el-icon><View /></el-icon>
                查看详情
              </el-button>
              <el-button 
                v-if="row.status === 'draft'" 
                type="warning" 
                size="small" 
                @click="handleEdit(row)"
              >
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button 
                v-if="row.status === 'draft'" 
                type="success" 
                size="small" 
                @click="handleSubmit(row)"
              >
                <el-icon><Upload /></el-icon>
                提交
              </el-button>
              <el-button 
                v-if="row.status === 'pending'" 
                type="danger" 
                size="small" 
                @click="handleWithdraw(row)"
              >
                <el-icon><Back /></el-icon>
                撤回
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="流程详情"
      width="900px"
      :close-on-click-modal="false"
    >
      <div v-if="currentDetail" class="detail-content">
        <div class="detail-header">
          <h3>{{ currentDetail.title }}</h3>
          <div class="detail-meta">
            <el-tag :type="getTypeTagType(currentDetail.type)" size="small">
              {{ getTypeLabel(currentDetail.type) }}
            </el-tag>
            <el-tag :type="getStatusTagType(currentDetail.status)" size="small">
              {{ getStatusLabel(currentDetail.status) }}
            </el-tag>
            <el-tag v-if="currentDetail.priority === 'high'" type="danger" size="small">
              紧急
            </el-tag>
            <span class="meta-item">申请人：{{ currentDetail.applicant }}</span>
            <span class="meta-item">创建时间：{{ formatTime(currentDetail.create_time) }}</span>
          </div>
        </div>
        
        <el-divider />
        
        <div class="detail-body">
          <h4>申请内容</h4>
          <div class="content-box">
            <p>{{ currentDetail.content }}</p>
          </div>
          
          <h4>申请信息</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="申请人">{{ currentDetail.applicant }}</el-descriptions-item>
            <el-descriptions-item label="申请时间">{{ formatTime(currentDetail.create_time) }}</el-descriptions-item>
            <el-descriptions-item label="当前审批人">{{ currentDetail.current_approver || '-' }}</el-descriptions-item>
            <el-descriptions-item label="优先级">
              <el-tag :type="currentDetail.priority === 'high' ? 'danger' : 'info'" size="small">
                {{ currentDetail.priority === 'high' ? '高' : '普通' }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
          
          <h4>审批流程</h4>
          <div class="approval-flow">
            <el-steps :active="getActiveStep(currentDetail.approval_steps)" direction="vertical">
              <el-step 
                v-for="(step, index) in currentDetail.approval_steps" 
                :key="index"
                :title="step.approver"
                :description="step.comment || '暂无意见'"
                :status="getStepStatus(step)"
              >
                <template #icon>
                  <el-icon v-if="step.status === 'approved'"><Check /></el-icon>
                  <el-icon v-else-if="step.status === 'rejected'"><Close /></el-icon>
                  <el-icon v-else-if="step.status === 'current'"><Clock /></el-icon>
                  <el-icon v-else><More /></el-icon>
                </template>
              </el-step>
            </el-steps>
          </div>
          
          <div v-if="currentDetail.attachments && currentDetail.attachments.length > 0">
            <h4>附件</h4>
            <div class="attachment-list">
              <div 
                v-for="file in currentDetail.attachments" 
                :key="file.id"
                class="attachment-item"
                @click="handleDownloadFile(file)"
              >
                <el-icon><Document /></el-icon>
                <span>{{ file.name }}</span>
                <el-tag size="small" type="info">{{ file.size }}</el-tag>
              </div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button 
            v-if="currentDetail && currentDetail.status === 'draft'" 
            type="warning" 
            @click="handleEdit(currentDetail)"
          >
            编辑
          </el-button>
          <el-button 
            v-if="currentDetail && currentDetail.status === 'draft'" 
            type="primary" 
            @click="handleSubmit(currentDetail)"
          >
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 创建/编辑对话框 -->
    <el-dialog
      v-model="formDialogVisible"
      :title="isEdit ? '编辑流程' : '新建流程'"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="workflowForm"
        :rules="formRules"
        label-width="100px"
        class="workflow-form"
      >
        <el-form-item label="流程标题" prop="title">
          <el-input
            v-model="workflowForm.title"
            placeholder="请输入流程标题"
          />
        </el-form-item>
        <el-form-item label="流程类型" prop="type">
          <el-select
            v-model="workflowForm.type"
            placeholder="请选择流程类型"
            style="width: 100%"
          >
            <el-option label="请假申请" value="leave" />
            <el-option label="报销申请" value="reimbursement" />
            <el-option label="出差申请" value="business" />
            <el-option label="采购申请" value="purchase" />
            <el-option label="其他申请" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-radio-group v-model="workflowForm.priority">
            <el-radio label="normal">普通</el-radio>
            <el-radio label="high">紧急</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="申请内容" prop="content">
          <el-input
            v-model="workflowForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入申请内容"
          />
        </el-form-item>
        <el-form-item label="附件">
          <el-upload
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
            :file-list="fileList"
            multiple
          >
            <el-button type="primary">
              <el-icon><Upload /></el-icon>
              选择文件
            </el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持 jpg/png/pdf/doc/docx 格式，单个文件不超过 10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="formDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleFormSubmit" :loading="submitLoading">
            {{ isEdit ? '保存' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang='ts'>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { 
  Search, Refresh, Plus, View, Edit, Upload, Back, 
  Check, Close, Clock, More, Document 
} from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const detailDialogVisible = ref(false)
const formDialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()
const workflowList = ref<any[]>([])
const total = ref(0)
const currentDetail = ref<any>(null)
const fileList = ref<any[]>([])

// 搜索表单
const searchForm = reactive({
  title: '',
  type: '',
  status: ''
})

// 分页配置
const pagination = reactive({
  page: 1,
  size: 10
})

// 流程表单
const workflowForm = reactive({
  id: '',
  title: '',
  type: '',
  priority: 'normal',
  content: '',
  attachments: []
})

// 表单验证规则
const formRules: FormRules = {
  title: [
    { required: true, message: '请输入流程标题', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择流程类型', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入申请内容', trigger: 'blur' }
  ]
}

// 方法
const loadWorkflowList = async () => {
  loading.value = true
  try {
    // 模拟API延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟数据
    const mockData = [
      {
        id: '1',
        title: '请假申请 - 年假3天',
        type: 'leave',
        status: 'approved',
        priority: 'normal',
        applicant: '张三',
        content: '因家中有事，申请年假3天，时间：2024-01-15 至 2024-01-17',
        current_approver: '-',
        create_time: Date.now() - 86400000 * 5,
        update_time: Date.now() - 86400000 * 2,
        approval_steps: [
          { approver: '李经理', status: 'approved', comment: '同意', time: Date.now() - 86400000 * 3 },
          { approver: '王总监', status: 'approved', comment: '同意', time: Date.now() - 86400000 * 2 }
        ],
        attachments: [
          { id: '1', name: '请假申请表.pdf', size: '256KB' }
        ]
      },
      {
        id: '2',
        title: '紧急出差申请',
        type: 'business',
        status: 'pending',
        priority: 'high',
        applicant: '李四',
        content: '紧急前往上海处理客户问题，预计出差2天',
        current_approver: '赵总监',
        create_time: Date.now() - 86400000 * 1,
        update_time: Date.now() - 86400000 * 1,
        approval_steps: [
          { approver: '王经理', status: 'approved', comment: '同意', time: Date.now() - 86400000 * 1 },
          { approver: '赵总监', status: 'current', comment: '', time: null }
        ],
        attachments: [
          { id: '2', name: '出差申请表.pdf', size: '128KB' },
          { id: '3', name: '客户问题说明.docx', size: '512KB' }
        ]
      },
      {
        id: '3',
        title: '办公设备采购申请',
        type: 'purchase',
        status: 'draft',
        priority: 'normal',
        applicant: '王五',
        content: '申请采购新办公设备，包括显示器、键盘等',
        current_approver: '-',
        create_time: Date.now() - 86400000 * 2,
        update_time: Date.now() - 86400000 * 2,
        approval_steps: [],
        attachments: [
          { id: '4', name: '采购清单.xlsx', size: '64KB' }
        ]
      },
      {
        id: '4',
        title: '报销申请 - 差旅费',
        type: 'reimbursement',
        status: 'rejected',
        priority: 'normal',
        applicant: '赵六',
        content: '出差期间产生的交通费、住宿费等费用报销',
        current_approver: '-',
        create_time: Date.now() - 86400000 * 10,
        update_time: Date.now() - 86400000 * 8,
        approval_steps: [
          { approver: '孙经理', status: 'rejected', comment: '发票不完整，请补充', time: Date.now() - 86400000 * 8 }
        ],
        attachments: [
          { id: '5', name: '发票清单.xlsx', size: '128KB' }
        ]
      }
    ]
    
    // 模拟分页和搜索
    let filteredData = mockData.filter(item => {
      if (searchForm.title && !item.title.includes(searchForm.title)) return false
      if (searchForm.type && item.type !== searchForm.type) return false
      if (searchForm.status && item.status !== searchForm.status) return false
      return true
    })
    
    const start = (pagination.page - 1) * pagination.size
    const end = start + pagination.size
    workflowList.value = filteredData.slice(start, end)
    total.value = filteredData.length
  } catch (error: any) {
    ElMessage.error(error.message || '获取流程列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadWorkflowList()
}

const handleReset = () => {
  Object.assign(searchForm, {
    title: '',
    type: '',
    status: ''
  })
  pagination.page = 1
  loadWorkflowList()
}

const handleRefresh = () => {
  loadWorkflowList()
}

const handleCreate = () => {
  isEdit.value = false
  resetForm()
  formDialogVisible.value = true
}

const handleEdit = (row: any) => {
  isEdit.value = true
  Object.assign(workflowForm, row)
  fileList.value = row.attachments || []
  formDialogVisible.value = true
}

const handleViewDetail = (row: any) => {
  currentDetail.value = row
  detailDialogVisible.value = true
}

const handleSubmit = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要提交流程 "${row.title}" 吗？`,
      '提交确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    loading.value = true
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    row.status = 'pending'
    row.update_time = Date.now()
    
    ElMessage.success('流程提交成功')
    if (detailDialogVisible.value) {
      detailDialogVisible.value = false
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('流程提交失败')
    }
  } finally {
    loading.value = false
  }
}

const handleWithdraw = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要撤回流程 "${row.title}" 吗？`,
      '撤回确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    loading.value = true
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    row.status = 'withdrawn'
    row.update_time = Date.now()
    
    ElMessage.success('流程撤回成功')
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('流程撤回失败')
    }
  } finally {
    loading.value = false
  }
}

const handleFileChange = (file: any) => {
  fileList.value.push(file)
}

const handleFormSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    if (isEdit.value) {
      ElMessage.success('流程更新成功')
    } else {
      ElMessage.success('流程创建成功')
    }
    
    formDialogVisible.value = false
    loadWorkflowList()
  } catch (error: any) {
    ElMessage.error(error.message || '操作失败')
  } finally {
    submitLoading.value = false
  }
}

const handleDownloadFile = (file: any) => {
  ElMessage.info(`下载文件：${file.name}`)
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  loadWorkflowList()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadWorkflowList()
}

const formatTime = (timestamp?: number) => {
  if (!timestamp) return '-'
  return new Date(timestamp).toLocaleString('zh-CN')
}

const getTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    leave: '请假申请',
    reimbursement: '报销申请',
    business: '出差申请',
    purchase: '采购申请',
    other: '其他申请'
  }
  return typeMap[type] || '未知类型'
}

const getTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    leave: 'warning',
    reimbursement: 'success',
    business: 'primary',
    purchase: 'info',
    other: 'info'
  }
  return typeMap[type] || 'info'
}

const getStatusLabel = (status: string) => {
  const statusMap: Record<string, string> = {
    draft: '草稿',
    pending: '审批中',
    approved: '已通过',
    rejected: '已拒绝',
    withdrawn: '已撤回'
  }
  return statusMap[status] || '未知状态'
}

const getStatusTagType = (status: string) => {
  const statusMap: Record<string, string> = {
    draft: 'info',
    pending: 'warning',
    approved: 'success',
    rejected: 'danger',
    withdrawn: 'info'
  }
  return statusMap[status] || 'info'
}

const getActiveStep = (steps: any[]) => {
  const currentStep = steps.findIndex(step => step.status === 'current')
  return currentStep >= 0 ? currentStep + 1 : steps.length
}

const getStepStatus = (step: any) => {
  if (step.status === 'approved') return 'success'
  if (step.status === 'rejected') return 'error'
  if (step.status === 'current') return 'process'
  return 'wait'
}

const resetForm = () => {
  Object.assign(workflowForm, {
    id: '',
    title: '',
    type: '',
    priority: 'normal',
    content: '',
    attachments: []
  })
  fileList.value = []
  formRef.value?.clearValidate()
}

// 生命周期
onMounted(() => {
  loadWorkflowList()
})
</script>

<style scoped lang='scss'>
.workflow-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .search-section {
    margin-bottom: 20px;
    
    .search-card {
      border-radius: 12px;
      border: none;
      
      .search-form {
        .el-form-item {
          margin-bottom: 16px;
        }
      }
    }
  }

  .table-section {
    .table-card {
      border-radius: 12px;
      border: none;
      
      .table-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .header-left {
          display: flex;
          align-items: center;
          gap: 12px;
          
          .table-title {
            font-size: 18px;
            font-weight: 600;
            color: #303133;
          }
        }
        
        .header-right {
          display: flex;
          gap: 12px;
        }
      }
      
      .workflow-table {
        margin-bottom: 20px;
        
        :deep(.el-table__header) {
          background-color: #fafafa;
        }
        
        :deep(.el-table__row:hover) {
          background-color: #f5f7fa;
        }
        
        .title-cell {
          display: flex;
          align-items: center;
          gap: 8px;
          
          .urgent-title {
            font-weight: 600;
            color: #f56c6c;
            cursor: pointer;
            
            &:hover {
              text-decoration: underline;
            }
          }
        }
      }
      
      .pagination-wrapper {
        display: flex;
        justify-content: center;
        padding-top: 20px;
      }
    }
  }
}

.detail-content {
  .detail-header {
    margin-bottom: 20px;
    
    h3 {
      margin: 0 0 12px 0;
      color: #303133;
      font-size: 18px;
    }
    
    .detail-meta {
      display: flex;
      align-items: center;
      gap: 16px;
      color: #606266;
      font-size: 14px;
      
      .meta-item {
        display: flex;
        align-items: center;
      }
    }
  }
  
  .detail-body {
    h4 {
      margin: 20px 0 12px 0;
      color: #303133;
      font-weight: 600;
    }
    
    .content-box {
      background-color: #f8f9fa;
      padding: 16px;
      border-radius: 8px;
      border-left: 4px solid #409eff;
      
      p {
        margin: 0;
        line-height: 1.6;
        color: #606266;
      }
    }
    
    .approval-flow {
      background-color: #f8f9fa;
      padding: 20px;
      border-radius: 8px;
      
      :deep(.el-steps) {
        .el-step__title {
          font-weight: 600;
        }
        
        .el-step__description {
          color: #606266;
          font-size: 13px;
        }
      }
    }
    
    .attachment-list {
      .attachment-item {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 8px 12px;
        border: 1px solid #e4e7ed;
        border-radius: 6px;
        margin-bottom: 8px;
        cursor: pointer;
        transition: all 0.3s;
        
        &:hover {
          background-color: #f5f7fa;
          border-color: #409eff;
        }
        
        .el-icon {
          color: #409eff;
        }
      }
    }
  }
}

.workflow-form {
  .el-form-item {
    margin-bottom: 20px;
  }
}

.dialog-footer {
  text-align: right;
}

// 响应式设计
@media (max-width: 768px) {
  .workflow-management {
    padding: 10px;
    
    .search-section .search-card .search-form {
      .el-form-item {
        display: block;
        margin-bottom: 12px;
        
        .el-form-item__content {
          margin-left: 0 !important;
        }
      }
    }
    
    .table-section .table-card .table-header {
      flex-direction: column;
      gap: 12px;
      align-items: flex-start;
    }
    
    .detail-content .detail-header .detail-meta {
      flex-direction: column;
      align-items: flex-start;
      gap: 8px;
    }
    
    .detail-content .detail-body .approval-flow {
      padding: 12px;
    }
  }
}
</style>
